package controllers

import "LoginTemplate/models"

type CommodityController struct {
	BaseController
}

type Commodity struct {
	ID            int    `json:"id"`
	CommodityName string `json:"commodity_name"`
}

// 添加分类
func (u *CommodityController) InsertCommodity() {
	var client Commodity
	err := u.ShouldBind(&client)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "insert into commodity ( commodity_name ) values (?)"
	tx := models.DB.Debug().Exec(sql, client.CommodityName)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

// 修改分类
func (u *CommodityController) UpdateCommodity() {
	var client Commodity
	err := u.ShouldBind(&client)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "update commodity set commodity_name = ? where id = ?"
	tx := models.DB.Debug().Exec(sql, client.CommodityName, client.ID)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

type CommodityData struct {
	Code        int         `json:"code"`
	Msg         string      `json:"msg"`
	Data        []Commodity `json:"data"`
	Sum         int         `json:"sum"`         //总页数
	CurrentPage int         `json:"currentPage"` //当前页
	TotalNumber int         `json:"totalNumber"` //总条数
}

// 查询分类
func (u *CommodityController) SelectCommodity() {
	var pictureList PictureList
	err := u.ShouldBind(&pictureList)
	var sum int
	var totalNumber int
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var client []Commodity
	sql := "select * from commodity limit ? , ?"
	tx := models.DB.Debug().Raw(sql, (pictureList.Page-1)*pictureList.Size, pictureList.Size).Scan(&client)
	sqlsum := "SELECT CEIL(COUNT(*) / ? ) FROM commodity"
	models.DB.Debug().Raw(sqlsum, pictureList.Size).Scan(&sum)
	sqlNumBer := "select count(*) from commodity"
	models.DB.Debug().Raw(sqlNumBer).Scan(&totalNumber)
	if tx.Error != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var picturedata CommodityData
	picturedata.Code = 200
	picturedata.Data = client
	picturedata.Msg = "成功"
	picturedata.Sum = sum
	picturedata.CurrentPage = pictureList.Page
	picturedata.TotalNumber = totalNumber
	//return picturedata
	u.JsonMsg(200, map[string]interface{}{
		"list":  picturedata,
		"count": "",
	}, "success")
}
